package com.relytosoft.mizar.media.analyze.services.service.behavior.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.relytosoft.dubhe.common.core.base.page.PageQuery;
import com.relytosoft.dubhe.common.core.exception.ServiceException;
import com.relytosoft.dubhe.common.core.utils.BeanCopyUtils;
import com.relytosoft.dubhe.common.satoken.entity.CurrentUser;
import com.relytosoft.mizar.media.analyze.api.entity.behavior.AyBehaviorTask;
import com.relytosoft.mizar.media.analyze.api.entity.behavior.AyBehaviorTaskSon;
import com.relytosoft.mizar.media.analyze.api.entity.behavior.AyEventType;
import com.relytosoft.mizar.media.analyze.api.pojo.dto.AyBehaviorTaskDto;
import com.relytosoft.mizar.media.analyze.api.pojo.query.AyBehaviorTaskQuery;
import com.relytosoft.mizar.media.analyze.api.pojo.vo.AyBatchVo;
import com.relytosoft.mizar.media.analyze.api.pojo.vo.AyBehaviorTaskVo;
import com.relytosoft.mizar.media.analyze.api.pojo.vo.AyCameraVo;
import com.relytosoft.mizar.media.analyze.api.pojo.vo.AyEventTypeVo;
import com.relytosoft.mizar.media.analyze.services.mapper.behavior.AyBehaviorTaskMapper;
import com.relytosoft.mizar.media.analyze.services.service.behavior.AyBehaviorTaskService;
import com.relytosoft.mizar.media.analyze.services.service.behavior.AyBehaviorTaskSonService;
import com.relytosoft.mizar.media.analyze.services.service.behavior.AyEventTypeService;
import com.relytosoft.mizar.media.common.config.properties.MizarAnalyzeProperties;
import com.relytosoft.mizar.media.common.enums.DeleteStatusEnum;
import com.relytosoft.mizar.media.common.enums.TaskStatusEnum;
import com.relytosoft.mizar.media.common.enums.TaskTypeEnum;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lj
 * @date 2022/6/7 10:06
 */
@Service
public class AyBehaviorTaskServiceImpl extends ServiceImpl<AyBehaviorTaskMapper, AyBehaviorTask> implements AyBehaviorTaskService {

    @Resource
    private AyBehaviorTaskSonService ayBehaviorTaskSonService;

    @Resource
    private MizarAnalyzeProperties analyzeProperties;

    @Resource
    private AyEventTypeService ayEventTypeService;


    @Override
    public Page<AyBehaviorTaskVo> selectAyBehaviorTaskPageList(PageQuery pageQuery, AyBehaviorTaskQuery ayBehaviorTaskQuery) {
        if (StrUtil.isBlank(pageQuery.getOrderByColumn())) {
            pageQuery.setOrderByColumn("id");
            pageQuery.setIsAsc("desc");
        }
        //获取所有正常状态的事件
        List<AyEventType> ayEventTypeList = ayEventTypeService.list(Wrappers.<AyEventType>lambdaQuery().eq(AyEventType::getStatus, 1));
        //收集parentId=0
        Map<String, String> algorithmMap =
                ayEventTypeList.stream().filter(e -> e.getParentId() == 0).collect(Collectors.toMap(e -> e.getCode() + "", AyEventType::getName));
        //收集parentId!=0
        Map<String, String> subtypesMap =
                ayEventTypeList.stream().filter(e -> e.getParentId() != 0).collect(Collectors.toMap(e -> e.getCode() + "", AyEventType::getName));
        Page<AyBehaviorTaskVo> page = baseMapper.selectPageTaskList(pageQuery.build(), ayBehaviorTaskQuery);
        List<AyBehaviorTaskVo> records = page.getRecords();
        //循环设置事件名称
        records.forEach(ayBehaviorTaskVo -> {
            ayBehaviorTaskVo.setAlgorithmName(algorithmMap.get(ayBehaviorTaskVo.getAlgorithmid()));
            ayBehaviorTaskVo.setSubtypeName(subtypesMap.get(ayBehaviorTaskVo.getSubtypes()));
        });
        return page;
    }


    @Override
    public AyBehaviorTask getAyBehaviorTask(AyBehaviorTaskDto ayBehaviorTaskDto) {
        // 获取需要添加的设备ID
        List<AyCameraVo> ayCameraVos = ayBehaviorTaskDto.getAyCameraVos();
        AyBatchVo ayBatchVo = new AyBatchVo();
        ayBatchVo.setTotal(ayCameraVos.size());
        // 添加任务前参数校验
        if (addFrontVerify(ayBehaviorTaskDto)) {
            ayBatchVo.setSuccess(0);
            ayBatchVo.setError(ayCameraVos.size());
            ayBatchVo.setErrorMsg(Collections.singletonList("没有符合创建条件的设备"));
            throw new ServiceException(JSONObject.toJSONString(ayBatchVo));
        }
        //构造AyBehaviorTask
        AyBehaviorTask ayBehaviorTask = BeanCopyUtils.copy(ayBehaviorTaskDto, AyBehaviorTask.class);
        ayBehaviorTask.setDeleted(DeleteStatusEnum.NOT_DELETED.getValue());
        ayBehaviorTask.setType(TaskTypeEnum.REAL_TIME.getValue());
        ayBehaviorTask.setLicenceUsing(0);
        ayBehaviorTask.setProgress(0);
        ayBehaviorTask.setIsStarting(0);
        ayBehaviorTask.setIsStartUp(0);
        if (ayBehaviorTask.getStatus() == TaskStatusEnum.CREATED.getValue()) {
            ayBehaviorTask.setStatus(TaskStatusEnum.RUNING.getValue());
            ayBehaviorTask.setBeginTime(LocalDateTime.now());
        }
        return ayBehaviorTask;
    }


    @Override
    public List<AyBehaviorTaskSon> getAyBehaviorTaskSon(AyBehaviorTask ayBehaviorTask) {
        //构建行为分析子任务
        ArrayList<AyBehaviorTaskSon> ayBehaviorTaskSonArrayList = new ArrayList<>();
        ayBehaviorTask.getAyCameraVos().forEach(item -> {
            AyBehaviorTaskSon ayBehaviorTaskSon = BeanCopyUtils.copy(ayBehaviorTask, AyBehaviorTaskSon.class);
            ayBehaviorTaskSon.setCameraId(item.getCameraId());
            ayBehaviorTaskSon.setIsDeleted(DeleteStatusEnum.NOT_DELETED.getValue());
            ayBehaviorTaskSon.setCameraName(item.getCameraName());
            ayBehaviorTaskSon.setVideoUrl(item.getVideoUrl());
            ayBehaviorTaskSon.setBehavior(0);
            ayBehaviorTaskSon.setIsSearchStatus(0);
            ayBehaviorTaskSonArrayList.add(ayBehaviorTaskSon);
        });
        return ayBehaviorTaskSonArrayList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveAyBehaviorTaskAndSon(AyBehaviorTask ayBehaviorTask, List<AyBehaviorTaskSon> ayBehaviorTaskSonList, AyBatchVo ayBatchVo) {
        //保存ayBehaviorTask
        boolean save = save(ayBehaviorTask);
        //如果保存成功
        if (save) {
            //循环ayBehaviorTaskSon设置behaviorTaskId
            ayBehaviorTaskSonList.forEach(item -> item.setBehaviorTaskId(ayBehaviorTask.getId()));
            //批量保存ayBehaviorTaskSonList
            save = ayBehaviorTaskSonService.saveBatch(ayBehaviorTaskSonList);
        }
        if (save) {
            ayBatchVo.setSuccess(ayBehaviorTaskSonList.size());
            ayBatchVo.setError(ayBatchVo.getTotal() - ayBehaviorTaskSonList.size());
        }
        return save;
    }

    @Override
    public List<AyBehaviorTask> checkDelete(List<Integer> ids) {
        //主任务删除校验
        if (!checkMainTaskDelete(ids)) {
            return null;
        }
        //子任务删除校验
        if (checkSonTaskDelete(ids)) {
            return null;
        }
        //创建需要删除的AyBehaviorTask集合
        List<AyBehaviorTask> ayBehaviorTaskList = new ArrayList<>();
        ids.forEach(id -> {
            AyBehaviorTask ayBehaviorTask = new AyBehaviorTask();
            ayBehaviorTask.setId(id);
            ayBehaviorTask.setDeleted(DeleteStatusEnum.DELETED.getValue());
            ayBehaviorTask.setUpdatedId(CurrentUser.getCurrentUserId());
            ayBehaviorTask.setUpdatedBy(CurrentUser.getCurrentUserName());
            ayBehaviorTaskList.add(ayBehaviorTask);
        });
        return ayBehaviorTaskList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteAyBehaviorTask(List<Integer> ids, List<AyBehaviorTask> ayBehaviorTaskList) {
        //批量删除主任务
        boolean update = this.updateBatchById(ayBehaviorTaskList, ayBehaviorTaskList.size());
        //判断主任务删除是否成功，如果成功，则删除子任务
        if (update) {
            //删除子任务
            update = ayBehaviorTaskSonService.deleteByMainTaskId(ids);
        }
        return update;
    }

    @Override
    public AyBatchVo checkStart(List<Integer> ids) {
        //如果ids为空，则抛出异常
        if (ids.isEmpty()) {
            throw new ServiceException("未选择任何任务");
        }
        //创建AyBatchVo，设置总数
        AyBatchVo ayBatchVo = new AyBatchVo();
        ayBatchVo.setTotal(ids.size());
        //查询可以启动的主任务
        List<AyBehaviorTask> ayBehaviorTaskList = selectCanStartMainTask(ids);
        //判断是否有可以启动的主任务
        if (ayBehaviorTaskList.isEmpty()) {
            ayBatchVo.setSuccess(0);
            ayBatchVo.setError(ids.size());
            ayBatchVo.setErrorMsg(Collections.singletonList("没有符合条件的任务"));
            return ayBatchVo;
        }
        //获取可以启动的主任务的id集合
        List<Integer> canStartIds = ayBehaviorTaskList.stream().map(AyBehaviorTask::getId).collect(Collectors.toList());
        ids.clear();
        ids.addAll(canStartIds);
        return ayBatchVo;
    }

    @Override
    public List<AyBehaviorTaskSon> selectCanStartSonTask(List<Integer> behaviorTaskId) {
        // 查询子任务未删除，状态为已结束、未启动、异常的任务列表
        LambdaQueryWrapper<AyBehaviorTaskSon> wrapper = new QueryWrapper<AyBehaviorTaskSon>().lambda();
        wrapper
                .eq(AyBehaviorTaskSon::getIsDeleted, DeleteStatusEnum.NOT_DELETED.getValue())
                .in(AyBehaviorTaskSon::getBehaviorTaskId, behaviorTaskId)
                .in(AyBehaviorTaskSon::getStatus, Arrays.asList(
                        TaskStatusEnum.FINISHED.getValue(),
                        TaskStatusEnum.NOT_STARTED.getValue(),
                        TaskStatusEnum.UNUSUAL.getValue()));
        return ayBehaviorTaskSonService.list(wrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void startTask(List<AyBehaviorTaskSon> ayBehaviorTaskSonList, AyBatchVo ayBatchVo, List<AyBehaviorTaskSon> insertTaskSons, List<AyBehaviorTaskSon> startTaskSons) {
        //获取主任务behaviorTaskId并去重
        List<Integer> behaviorTaskIds = ayBehaviorTaskSonList
                .stream()
                .map(AyBehaviorTaskSon::getBehaviorTaskId)
                .distinct()
                .collect(Collectors.toList());

        //记录成功个数
        Integer successNumber = 0;

        //循环behaviorTaskIds
        for (Integer behaviorTaskId : behaviorTaskIds) {
            //获取已结束，未删除的子任务集合
            List<AyBehaviorTaskSon> deleteTaskSons = new ArrayList<>();
            //获取已结束，未删除的子任务并封装为需要添加的子任务集合
            List<AyBehaviorTaskSon> insertTask = new ArrayList<>();
            //获取异常、未启动、未删除的子任务
            List<AyBehaviorTaskSon> startTask = new ArrayList<>();
            //当前主任务的子任务集合
            List<AyBehaviorTaskSon> currentTaskSons = ayBehaviorTaskSonList
                    .stream()
                    .filter(ayBehaviorTaskSon -> Objects.equals(ayBehaviorTaskSon.getBehaviorTaskId(), behaviorTaskId))
                    .collect(Collectors.toList());
            //根据currentTaskSons构建deleteTaskSons和insertTaskSons
            buildNeedInsertAndDeleteTaskSons(currentTaskSons, deleteTaskSons, insertTask);
            //根据currentTaskSons构建startTaskSons
            buildStartTaskSons(currentTaskSons, startTask);
            //构建主任务信息
            AyBehaviorTask ayBehaviorTask = new AyBehaviorTask();
            ayBehaviorTask.setId(behaviorTaskId);
//            ayBehaviorTask.setStatus(TaskStatusEnum.CREATED.getValue());
            ayBehaviorTask.setStatus(TaskStatusEnum.RUNING.getValue());
            //更新本数据库的主任务和子任务
            if (startMainTaskAndSonTask(ayBehaviorTask, startTask, insertTask, deleteTaskSons)) {
                successNumber++;
            }
            //分别给insertTaskSons和startTaskSons赋值
            insertTaskSons.addAll(insertTask);
            startTaskSons.addAll(startTask);
        }
        ayBatchVo.setSuccess(successNumber);
        ayBatchVo.setError(ayBatchVo.getTotal() - ayBatchVo.getSuccess());
    }

    @Override
    public AyBatchVo checkStop(List<Integer> ids) {
        //1. 判断ids是否为空
        if (ids.isEmpty()) {
            throw new ServiceException("未选择任何任务");
        }
        //2. 创建AyBatchVo，设置总数
        AyBatchVo ayBatchVo = new AyBatchVo();
        ayBatchVo.setTotal(ids.size());
        //3. 查询可以停止的主任务
        List<AyBehaviorTask> ayBehaviorTaskList = selectCanStopMainTask(ids);
        //4. 判断是否有可以停止的主任务
        if (ayBehaviorTaskList.isEmpty()) {
            ayBatchVo.setSuccess(0);
            ayBatchVo.setError(ids.size());
            ayBatchVo.setErrorMsg(Collections.singletonList("没有符合条件的任务"));
            return ayBatchVo;
        }
        //5. 获取可以停止的主任务的id集合
        List<Integer> canStopIds = ayBehaviorTaskList.stream().map(AyBehaviorTask::getId).collect(Collectors.toList());
        ids.clear();
        ids.addAll(canStopIds);
        return ayBatchVo;
    }

    @Override
    public List<AyBehaviorTaskSon> selectCanStopSonTask(List<Integer> behaviorTaskIds) {
        //1. 构造查询条件
        LambdaQueryWrapper<AyBehaviorTaskSon> wrapper = new QueryWrapper<AyBehaviorTaskSon>().lambda();
        wrapper
                .eq(AyBehaviorTaskSon::getIsDeleted, DeleteStatusEnum.NOT_DELETED.getValue())
                .in(AyBehaviorTaskSon::getBehaviorTaskId, behaviorTaskIds)
                .and(item -> item
                        .eq(AyBehaviorTaskSon::getStatus, TaskStatusEnum.RUNING.getValue())
                        .or(item2 -> item2
                                .eq(AyBehaviorTaskSon::getStatus, TaskStatusEnum.CREATED.getValue())
                                .lt(AyBehaviorTaskSon::getUpdatedTime, LocalDateTime.now().plusSeconds(-1L * analyzeProperties.getTaskCanStopTime()))));
        return ayBehaviorTaskSonService.list(wrapper);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void stopTask(List<AyBehaviorTaskSon> ayBehaviorTaskSonList, AyBatchVo ayBatchVo, List<AyBehaviorTaskSon> stopTaskSons) {
        //获取主任务behaviorTaskId并去重
        List<Integer> behaviorTaskIds = ayBehaviorTaskSonList
                .stream()
                .map(AyBehaviorTaskSon::getBehaviorTaskId)
                .distinct()
                .collect(Collectors.toList());
        //记录成功个数
        Integer successNumber = 0;
        //循环behaviorTaskIds
        for (Integer behaviorTaskId : behaviorTaskIds) {
            //停止任务
            List<AyBehaviorTaskSon> stopTask = new ArrayList<>();
            //当前主任务的子任务集合
            List<AyBehaviorTaskSon> currentTaskSons = ayBehaviorTaskSonList
                    .stream()
                    .filter(ayBehaviorTaskSon -> Objects.equals(ayBehaviorTaskSon.getBehaviorTaskId(), behaviorTaskId))
                    .collect(Collectors.toList());
            //根据currentTaskSons构建stopTaskSons
            buildStopTaskSons(currentTaskSons, stopTask);
            //构建主任务信息,状态，更新人，更新人ID,结束时间
            AyBehaviorTask ayBehaviorTask = new AyBehaviorTask();
            ayBehaviorTask.setId(behaviorTaskId);
            ayBehaviorTask.setStatus(TaskStatusEnum.FINISHED.getValue());
            ayBehaviorTask.setUpdatedBy(CurrentUser.getCurrentUserFullName());
            ayBehaviorTask.setUpdatedId(CurrentUser.getCurrentUserId());
            ayBehaviorTask.setEndTime(LocalDateTime.now());
            //更新本数据库的主任务和子任务
            if (stopMainTaskAndSonTask(ayBehaviorTask, stopTask)) {
                successNumber++;
            }
            //stopTaskSons赋值
            stopTaskSons.addAll(stopTask);
        }
        ayBatchVo.setSuccess(successNumber);
        ayBatchVo.setError(ayBatchVo.getTotal() - ayBatchVo.getSuccess());
    }

    @Override
    public List<JSONObject> selectAyBehaviorList() {
        //构造查询条件,deleted=0,只查询name和id
        LambdaQueryWrapper<AyBehaviorTask> wrapper = new QueryWrapper<AyBehaviorTask>().lambda();
        wrapper
                .select(AyBehaviorTask::getId, AyBehaviorTask::getName)
                .eq(AyBehaviorTask::getDeleted, DeleteStatusEnum.NOT_DELETED.getValue());
        //查询数据
        List<AyBehaviorTask> ayBehaviorTaskList = this.list(wrapper);
        return ayBehaviorTaskList.stream().map(ayBehaviorTask -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", ayBehaviorTask.getId());
            jsonObject.put("name", ayBehaviorTask.getName());
            return jsonObject;
        }).collect(Collectors.toList());
    }

    @Override
    public void taskStatusHandle(Integer behaviorTaskId, int newStatus) {
        //获取当前updateBY
        String updateBy = CurrentUser.getCurrentUserFullName();
        //判断是否是为空
        if (StrUtil.isEmpty(updateBy)) {
            updateBy = "SYSTEM";
        }
        if (newStatus == TaskStatusEnum.CREATED.getValue()) {
            //启动成功联动处理主任务状态
            //构建查询条件LambdaUpdateWrapper
            LambdaUpdateWrapper<AyBehaviorTask> wrapper = new UpdateWrapper<AyBehaviorTask>().lambda();
            wrapper
                    .set(AyBehaviorTask::getStatus, newStatus)
                    .set(AyBehaviorTask::getUpdatedBy, updateBy)
                    .set(AyBehaviorTask::getUpdatedId, CurrentUser.getCurrentUserId())
                    .set(AyBehaviorTask::getEndTime, null)
                    .set(AyBehaviorTask::getBeginTime, LocalDateTime.now())

                    .eq(AyBehaviorTask::getId, behaviorTaskId)
                    .eq(AyBehaviorTask::getDeleted, DeleteStatusEnum.NOT_DELETED.getValue())
                    .in(AyBehaviorTask::getStatus, TaskStatusEnum.FINISHED.getValue(), TaskStatusEnum.NOT_STARTED.getValue(), TaskStatusEnum.UNUSUAL.getValue());
            //更新数据
            this.update(wrapper);
        } else if (newStatus == TaskStatusEnum.FINISHED.getValue()) {
            //查询子任务状态是否有创建中,运行中且未删除的子任务
            LambdaQueryWrapper<AyBehaviorTaskSon> wrapper = new QueryWrapper<AyBehaviorTaskSon>().lambda();
            wrapper
                    .eq(AyBehaviorTaskSon::getBehaviorTaskId, behaviorTaskId)
                    .eq(AyBehaviorTaskSon::getIsDeleted, DeleteStatusEnum.NOT_DELETED.getValue())
                    .in(AyBehaviorTaskSon::getStatus, TaskStatusEnum.CREATED.getValue(), TaskStatusEnum.RUNING.getValue());
            //查询数量，并判断是否为0
            if (ayBehaviorTaskSonService.count(wrapper) == 0) {
                //创建主任务对象
                AyBehaviorTask ayBehaviorTask = new AyBehaviorTask();
                ayBehaviorTask.setId(behaviorTaskId);
                ayBehaviorTask.setStatus(newStatus);
                ayBehaviorTask.setEndTime(LocalDateTime.now());
                //更新主任务
                this.updateById(ayBehaviorTask);
            }
        } else if (newStatus == TaskStatusEnum.RUNING.getValue()) {
            //查询子任务状态是否有创建中,异常且未删除的子任务
            LambdaQueryWrapper<AyBehaviorTaskSon> wrapper = new QueryWrapper<AyBehaviorTaskSon>().lambda();
            wrapper
                    .eq(AyBehaviorTaskSon::getBehaviorTaskId, behaviorTaskId)
                    .in(AyBehaviorTaskSon::getIsDeleted, TaskStatusEnum.CREATED, TaskStatusEnum.UNUSUAL)
                    .eq(AyBehaviorTaskSon::getIsDeleted, DeleteStatusEnum.NOT_DELETED.getValue());
            //查询任务数量
            long count = ayBehaviorTaskSonService.count(wrapper);
            if (count == 0) {
                //构造该主任务未删除，且运行中的查询条件
                LambdaQueryWrapper<AyBehaviorTask> wrapper1 = new QueryWrapper<AyBehaviorTask>().lambda();
                wrapper1
                        .eq(AyBehaviorTask::getId, behaviorTaskId)
                        .eq(AyBehaviorTask::getDeleted, DeleteStatusEnum.NOT_DELETED.getValue())
                        .eq(AyBehaviorTask::getStatus, TaskStatusEnum.RUNING.getValue());
                //创建主任务对象
                AyBehaviorTask ayBehaviorTask = new AyBehaviorTask();
                ayBehaviorTask.setStatus(newStatus);
                ayBehaviorTask.setUpdatedBy(updateBy);
                //更新主任务
                this.update(ayBehaviorTask, wrapper1);
            }
        }
    }

    @Override
    public List<AyEventTypeVo> selectEventByParentId(Integer parentId) {
        //构造查询条件
        LambdaQueryWrapper<AyEventType> wrapper = new QueryWrapper<AyEventType>().lambda();
        wrapper
                .eq(AyEventType::getParentId, parentId)
                .eq(AyEventType::getStatus, 1);
        //查询数据
        List<AyEventType> ayEventTypeList = ayEventTypeService.list(wrapper);
        ArrayList<AyEventTypeVo> resultList = new ArrayList<>();
        //复制
        ayEventTypeList.forEach(ayEventType -> {
            AyEventTypeVo ayEventTypeVo = BeanCopyUtils.copy(ayEventType, AyEventTypeVo.class);
            resultList.add(ayEventTypeVo);
        });
        return resultList;
    }


    private boolean stopMainTaskAndSonTask(AyBehaviorTask ayBehaviorTask, List<AyBehaviorTaskSon> stopTaskSons) {
        //更新主任务
        boolean update = this.updateById(ayBehaviorTask);
        if (update) {
            //停止子任务
            update = ayBehaviorTaskSonService.stopSonTask(stopTaskSons, ayBehaviorTask.getId());
            if (!update) {
                throw new ServiceException("更新子任务失败");
            }
        }
        return update;
    }

    private void buildStopTaskSons(List<AyBehaviorTaskSon> currentTaskSons, List<AyBehaviorTaskSon> stopTaskSons) {
        //currentTaskSons构建stopTaskSons
        currentTaskSons.forEach(ayBehaviorTaskSon -> {
            AyBehaviorTaskSon stopAyBehaviorTaskSon = new AyBehaviorTaskSon();
            stopAyBehaviorTaskSon.setId(ayBehaviorTaskSon.getId());
            stopAyBehaviorTaskSon.setStatus(TaskStatusEnum.FINISHED.getValue());
            stopAyBehaviorTaskSon.setTaskId(ayBehaviorTaskSon.getTaskId());
            stopAyBehaviorTaskSon.setEndTime(LocalDateTime.now());
            stopTaskSons.add(stopAyBehaviorTaskSon);
        });
    }

    private List<AyBehaviorTask> selectCanStopMainTask(List<Integer> ids) {
        //未删除,在运行中或创建中，更新时间已过指定配置的任务
        LambdaQueryWrapper<AyBehaviorTask> wrapper = new QueryWrapper<AyBehaviorTask>().lambda();
        wrapper
                .eq(AyBehaviorTask::getDeleted, DeleteStatusEnum.NOT_DELETED.getValue())
                .in(AyBehaviorTask::getId, ids)
                .and(item -> item
                        .eq(AyBehaviorTask::getStatus, TaskStatusEnum.RUNING.getValue())
                        .or(item1 -> item1
                                .eq(AyBehaviorTask::getStatus, TaskStatusEnum.CREATED.getValue())
                                .lt(AyBehaviorTask::getUpdatedTime, LocalDateTime.now().plusSeconds(-1L * analyzeProperties.getTaskCanStopTime()))));
        return this.list(wrapper);
    }


    private boolean startMainTaskAndSonTask(AyBehaviorTask ayBehaviorTask, List<AyBehaviorTaskSon> startTaskSons, List<AyBehaviorTaskSon> insertTaskSons, List<AyBehaviorTaskSon> deleteTaskSons) {
        //更新主任务信息
        LambdaUpdateWrapper<AyBehaviorTask> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .set(AyBehaviorTask::getStatus, TaskStatusEnum.RUNING.getValue())
                .set(AyBehaviorTask::getUpdatedId, CurrentUser.getCurrentUserId())
                .set(AyBehaviorTask::getUpdatedTime, LocalDateTime.now())
                .set(AyBehaviorTask::getUpdatedBy, CurrentUser.getCurrentUserName())
                .set(AyBehaviorTask::getBeginTime, LocalDateTime.now())
                .set(AyBehaviorTask::getEndTime, null)

                .eq(AyBehaviorTask::getId, ayBehaviorTask.getId())
                .eq(AyBehaviorTask::getDeleted, DeleteStatusEnum.NOT_DELETED.getValue())
                .in(AyBehaviorTask::getStatus, Arrays.asList(
                        TaskStatusEnum.FINISHED.getValue(),
                        TaskStatusEnum.NOT_STARTED.getValue(),
                        TaskStatusEnum.UNUSUAL.getValue()));
        boolean result = baseMapper.update(null, updateWrapper) == 1;
        if (result) {
            //删除已结束，未删除的子任务deleteTaskSons，并插入insertTaskSons
            if (!deleteTaskSons.isEmpty()) {
                result = ayBehaviorTaskSonService.deleteAndInsertTaskSons(deleteTaskSons, insertTaskSons, ayBehaviorTask.getId());
            }
            if (!startTaskSons.isEmpty()) {
                result = ayBehaviorTaskSonService.updateNeedStartTaskSons(startTaskSons, ayBehaviorTask.getId());
            }
            //如果result为false，抛出异常
            if (!result) {
                throw new RuntimeException("启动任务失败");
            }
        }
        return result;
    }

    private void buildStartTaskSons(List<AyBehaviorTaskSon> currentTaskSons, List<AyBehaviorTaskSon> startTaskSons) {
        //过滤出currentTaskSons中的异常、未启动、未删除的子任务,并创建AyBehaviorTaskSon对象，添加到startTaskSons
        currentTaskSons.stream()
                .filter(ayBehaviorTaskSon ->
                        Objects.equals(ayBehaviorTaskSon.getStatus(), TaskStatusEnum.UNUSUAL.getValue()) ||
                                Objects.equals(ayBehaviorTaskSon.getStatus(), TaskStatusEnum.NOT_STARTED.getValue()))
                .forEach(ayBehaviorTaskSon -> {
                    AyBehaviorTaskSon startBehaviorTaskSon = BeanCopyUtils.copy(ayBehaviorTaskSon, AyBehaviorTaskSon.class);
//                    startBehaviorTaskSon.setStatus(TaskStatusEnum.CREATED.getValue());
                    startBehaviorTaskSon.setStatus(TaskStatusEnum.RUNING.getValue());
                    startBehaviorTaskSon.setBeginTime(LocalDateTime.now());
                    startTaskSons.add(startBehaviorTaskSon);
                });
    }

    private void buildNeedInsertAndDeleteTaskSons(List<AyBehaviorTaskSon> currentTaskSons, List<AyBehaviorTaskSon> deleteTaskSons, List<AyBehaviorTaskSon> insertTaskSons) {
        //过滤出状态为已完成的值
        List<AyBehaviorTaskSon> finishedTaskSons = currentTaskSons
                .stream()
                .filter(ayBehaviorTaskSon -> Objects.equals(ayBehaviorTaskSon.getStatus(), TaskStatusEnum.FINISHED.getValue()))
                .collect(Collectors.toList());

        //构建deleteTaskSons
        finishedTaskSons.forEach(ayBehaviorTaskSon -> {
            AyBehaviorTaskSon deleteAyBehaviorTaskSon = new AyBehaviorTaskSon();
            deleteAyBehaviorTaskSon.setId(ayBehaviorTaskSon.getId());
            deleteAyBehaviorTaskSon.setIsDeleted(DeleteStatusEnum.DELETED.getValue());
            deleteTaskSons.add(deleteAyBehaviorTaskSon);
        });

        //构建insertTaskSons
        finishedTaskSons.forEach(ayBehaviorTaskSon -> {
            AyBehaviorTaskSon insertAyBehaviorTaskSon = new AyBehaviorTaskSon();
            insertAyBehaviorTaskSon.setBehaviorTaskId(ayBehaviorTaskSon.getBehaviorTaskId());
            insertAyBehaviorTaskSon.setBehavior(ayBehaviorTaskSon.getBehavior());
            insertAyBehaviorTaskSon.setIsDeleted(DeleteStatusEnum.NOT_DELETED.getValue());
//            insertAyBehaviorTaskSon.setStatus(TaskStatusEnum.CREATED.getValue());
            insertAyBehaviorTaskSon.setStatus(TaskStatusEnum.RUNING.getValue());
            insertAyBehaviorTaskSon.setVideoUrl(ayBehaviorTaskSon.getVideoUrl());
            insertAyBehaviorTaskSon.setCameraName(ayBehaviorTaskSon.getCameraName());
            insertAyBehaviorTaskSon.setCameraId(ayBehaviorTaskSon.getCameraId());
            insertAyBehaviorTaskSon.setBeginTime(LocalDateTime.now());
            insertAyBehaviorTaskSon.setType(ayBehaviorTaskSon.getType());
            insertAyBehaviorTaskSon.setAlgorithmid(ayBehaviorTaskSon.getAlgorithmid());
            insertAyBehaviorTaskSon.setSubtypes(ayBehaviorTaskSon.getSubtypes());
            insertAyBehaviorTaskSon.setLicenceUsing(ayBehaviorTaskSon.getLicenceUsing());
            insertAyBehaviorTaskSon.setIsSearchStatus(ayBehaviorTaskSon.getIsSearchStatus());
            insertAyBehaviorTaskSon.setRemark(ayBehaviorTaskSon.getRemark());
            insertTaskSons.add(insertAyBehaviorTaskSon);
        });
    }


    private List<AyBehaviorTask> selectCanStartMainTask(List<Integer> ids) {
        // 查询主任务未删除，状态为已结束、未启动、异常的任务列表
        return this.list(Wrappers.<AyBehaviorTask>lambdaQuery()
                .eq(AyBehaviorTask::getDeleted, DeleteStatusEnum.NOT_DELETED.getValue())
                .in(ids.size() > 0, AyBehaviorTask::getId, ids)
                .in(AyBehaviorTask::getStatus, TaskStatusEnum.FINISHED.getValue(), TaskStatusEnum.NOT_STARTED.getValue(), TaskStatusEnum.UNUSUAL.getValue())
        );
    }

    private boolean checkSonTaskDelete(List<Integer> ids) {
        //查询出ids中不能删除的子任务，运行中、创建中的子任务不允许删除
        LambdaQueryWrapper<AyBehaviorTaskSon> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(AyBehaviorTaskSon::getBehaviorTaskId, ids);
        wrapper.eq(AyBehaviorTaskSon::getIsDeleted, DeleteStatusEnum.NOT_DELETED.getValue());
        wrapper.in(AyBehaviorTaskSon::getStatus, TaskStatusEnum.RUNING.getValue(), TaskStatusEnum.CREATED.getValue());
        List<AyBehaviorTaskSon> ayBehaviorTaskSonList = ayBehaviorTaskSonService.list(wrapper);
        //判断ayBehaviorTaskSonList是否为空
        if (CollectionUtil.isNotEmpty(ayBehaviorTaskSonList)) {
            //获取ayBehaviorTaskSonList中的behaviorTaskId
            List<Integer> behaviorTaskIds = ayBehaviorTaskSonList.stream().map(AyBehaviorTaskSon::getBehaviorTaskId).collect(Collectors.toList());
            //去除ids中重复的behaviorTaskId
            ids.removeAll(behaviorTaskIds);
        }
        //返回ids是否为空
        return CollectionUtil.isEmpty(ids);
    }

    private boolean checkMainTaskDelete(List<Integer> ids) {
        if (ids == null || ids.size() == 0) {
            return false;
        }
        //获取ids中未删除的已结束、未启动、异常任务
        LambdaQueryWrapper<AyBehaviorTask> wrapper = new QueryWrapper<AyBehaviorTask>().lambda();
        wrapper.in(AyBehaviorTask::getId, ids);
        wrapper.eq(AyBehaviorTask::getDeleted, DeleteStatusEnum.NOT_DELETED.getValue());
        wrapper.in(AyBehaviorTask::getStatus, TaskStatusEnum.FINISHED.getValue(), TaskStatusEnum.UNUSUAL.getValue(), TaskStatusEnum.NOT_STARTED.getValue());
        //根据ID获取可删除的任务
        List<AyBehaviorTask> ayBehaviorTaskList = list(wrapper);
        if (ayBehaviorTaskList.isEmpty()) {
            return false;
        }
        //获取可删除的任务ID
        List<Integer> deleteIds = ayBehaviorTaskList.stream().map(AyBehaviorTask::getId).collect(Collectors.toList());
        //deleteIds赋值到ids中并返回
        ids.clear();
        ids.addAll(deleteIds);
        return true;
    }

    /**
     * 添加前参数校验
     *
     * @param ayBehaviorTaskDto 参数
     * @return 校验结果
     */
    private boolean addFrontVerify(AyBehaviorTaskDto ayBehaviorTaskDto) {
        // 获取需要添加的设备信息
        List<AyCameraVo> ayCameraVos = ayBehaviorTaskDto.getAyCameraVos();
        // 校验参数
        Iterator<AyCameraVo> iterator = ayCameraVos.iterator();
        if (iterator.hasNext()) {
            //同一通道、同一事件只能有一个未删除的行为分析任务
            LambdaQueryWrapper<AyBehaviorTaskSon> wrapper = new QueryWrapper<AyBehaviorTaskSon>().lambda();
            wrapper
                    .eq(AyBehaviorTaskSon::getCameraId, iterator.next().getCameraId())
                    .eq(AyBehaviorTaskSon::getIsDeleted, DeleteStatusEnum.NOT_DELETED.getValue())
                    .eq(AyBehaviorTaskSon::getSubtypes, ayBehaviorTaskDto.getSubtypes());
            AyBehaviorTaskSon ayBehaviorTaskSonServiceOne = ayBehaviorTaskSonService.getOne(wrapper);
            //如果ayBehaviorTaskSonServiceOne不为null,移除当前设备
            if (ayBehaviorTaskSonServiceOne != null) {
                iterator.remove();
            }
        }
        return ayCameraVos.isEmpty();
    }

}
